package com.study.springbootsecurity.config;

import com.study.springbootsecurity.config.properties.JwtConfigProperties;
import com.study.springbootsecurity.filter.sms.SmsCodeAuthenticationFilter;
import com.study.springbootsecurity.filter.sms.SmsCodeAuthenticationProvider;
import com.study.springbootsecurity.handler.sms.SmsCodeAuthenticationFailureHandler;
import com.study.springbootsecurity.handler.sms.SmsCodeAuthenticationSuccessHandler;
import com.study.springbootsecurity.service.impl.TokenService;
import com.study.springbootsecurity.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Description: TODO
 * @author: Huangjianyun
 * @date: 2025-06-14 21:09
 */
//@Component
public class SmsCodeAuthenticationSecurityConfig implements SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    TokenService tokenService;

    @Autowired
    JwtConfigProperties jwtConfigProperties;

    @Override
    public void init(HttpSecurity builder) throws Exception {

    }

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        SmsCodeAuthenticationFilter smsAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        smsAuthenticationFilter.setAuthenticationSuccessHandler(smsCodeAuthenticationSuccessHandler());
        smsAuthenticationFilter.setAuthenticationFailureHandler(smsCodeAuthenticationFailureHandler());
        SmsCodeAuthenticationProvider smsAuthenticationProvider = new SmsCodeAuthenticationProvider(userDetailsService,redisCache);
        builder.authenticationProvider(smsAuthenticationProvider)
                .addFilterBefore(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }


    public SmsCodeAuthenticationSuccessHandler smsCodeAuthenticationSuccessHandler() {
        return new SmsCodeAuthenticationSuccessHandler(jwtConfigProperties,tokenService,redisCache);
    }


    public SmsCodeAuthenticationFailureHandler smsCodeAuthenticationFailureHandler() {
        return new SmsCodeAuthenticationFailureHandler();
    }

}
